package com.stockz.ui.swing.watchlist.widget;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JPanel;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.ui.swing.core.menu.ViewMenu;
import com.stockz.ui.swing.widget.JButton;
import com.stockz.ui.swing.widget.JMenu;
import com.stockz.ui.swing.widget.JMenuItem;
import com.stockz.watchlist.manager.WatchListManager;
import com.stockz.watchlist.model.WatchList;

@Component
public class ShowWatchListMenu extends JMenu 
implements AddWatchListToUICallback, 
RemoveWatchListFromUICallback, InitializingBean{
	private static final long serialVersionUID = -7862722515649312857L;

	@Autowired
	private ViewMenu viewMenu;
	@Autowired
	private WatchListManager watchListManager;
	@Autowired
	private ShowWatchListActionListener showWatchListActionListener;
	@Autowired
	private RemoveWatchListActionListener removeWatchListActionListener;
	@Autowired
	private ExportWatchListMenuItem exportWatchListMenuItem;
	@Autowired
	private ImportWatchListMenuItem importWatchListMenuItem;
	
	public ShowWatchListMenu() {
		super("WatchList");
		setMnemonic(KeyEvent.VK_W);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		viewMenu.add(this);
		removeWatchListActionListener.setCallback(this);
		add(exportWatchListMenuItem);
		addSeparator();
		add(importWatchListMenuItem);
		addSeparator();
		addExistingWatchListsToMenu();
	}
	
	private void addExistingWatchListsToMenu(){
		List<WatchList> watchListList = watchListManager.getAll();
		if(watchListList != null){
			for(WatchList watchList : watchListList){
				addWatchListToUI(watchList);
			}
		}
	}
	
	@Override
	public void addWatchListToUI(WatchList watchList) {
		JMenuItem item = new JMenuItem();
		item.add(createPanel(watchList),BorderLayout.CENTER);
		item.setPayload(watchList);
		item.addActionListener(showWatchListActionListener);
		addSeparator();
		add(item);
	}
	
	private JPanel createPanel(WatchList watchList){
		JPanel panel = new JPanel();
		panel.add(new JLabel(watchList.getName()),BorderLayout.CENTER);
		JButton button = new JButton("x");
		button.setPayload(watchList);
		button.setPreferredSize(new Dimension(10,10));
		button.addActionListener(removeWatchListActionListener);
		panel.add(button,BorderLayout.EAST);
		return panel;
	}
	
	@Override
	public void removeFromUI(WatchList watchList) {
		int count = getItemCount();
		for(int i = 0; i < count; i++){
			JMenuItem item = (JMenuItem)getItem(i);
			if(item != null && item.getPayload() == null){
				remove(item);
			}
		}
	}
	
}
